package com.example.day13_7_13_2;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class MySqllite extends SQLiteOpenHelper {
    public MySqllite(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table student(id int,name text,age int)");
    }

    public void insert(Student student){
        SQLiteDatabase writableDatabase = getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("id",student.getId());
        contentValues.put("name",student.getName());
        contentValues.put("age",student.getAge());
        writableDatabase.insert("student",null,contentValues);
    }

    public List<Student> queryAll(){
        SQLiteDatabase writableDatabase = getWritableDatabase();
        List<Student> list = new ArrayList<>();
        Cursor cursor = writableDatabase.query("student", null, null, null, null, null, null);
        while (cursor.moveToNext()){
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            int age = cursor.getInt(cursor.getColumnIndex("age"));
            Student student = new Student(id, name, age);
            list.add(student);
        }
        return list;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void delete(Student student) {
        SQLiteDatabase writableDatabase = getWritableDatabase();
        writableDatabase.delete("student","name = ?",new String[]{student.getName()});
    }
}
